<template>
    <div class="tab-content">
        <!-- 标点列表 -->
        <div class="map-points-header">
            <h3>地图标点列表</h3>
            <el-button type="primary" @click="openAddPointDialog">添加标点</el-button>
        </div>

        <el-table :data="securityForm.mapPoints" border style="width: 100%; margin-bottom: 20px;">
            <el-table-column prop="name" label="点位名称" />
            <el-table-column prop="type" label="点位类型">
                <template #default="{ row }">
                    <el-tag
                        :type="getPointTypeTag(row.type) as 'success' | 'warning' | 'info' | 'primary' | 'danger'">{{
                        getPointTypeName(row.type) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="longitude" label="经度" />
            <el-table-column prop="latitude" label="纬度" />
            <el-table-column label="操作">
                <template #default="{ row, $index }">
                    <el-button size="small" type="primary" @click="editPoint(row, $index)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deletePoint($index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 标点配置弹窗 -->
        <el-dialog v-model="pointDialogVisible" title="标点配置" width="800px" class="point-dialog">
            <div class="dialog-content">
                <div class="form-section">
                    <h4>标点信息</h4>
                    <el-form ref="pointFormRef" :model="pointForm" :rules="pointRules" label-width="100px">
                        <el-form-item label="点位名称" prop="name">
                            <el-input v-model="pointForm.name" placeholder="请输入点位名称" />
                        </el-form-item>
                        <el-form-item label="点位类型" prop="type">
                            <el-select v-model="pointForm.type" placeholder="请选择点位类型">
                                <el-option label="绿电供应" value="solar" />
                                <el-option label="共享换点" value="battery" />
                                <el-option label="共享出行" value="travel" />
                                <el-option label="共享运力" value="transport" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="经度" prop="longitude">
                            <el-input-number v-model="pointForm.longitude" :precision="6"
                                placeholder="请输入经度" style="width: 100%" />
                        </el-form-item>
                        <el-form-item label="纬度" prop="latitude">
                            <el-input-number v-model="pointForm.latitude" :precision="6" placeholder="请输入纬度"
                                style="width: 100%" />
                        </el-form-item>
                    </el-form>
                </div>

                <div class="map-section">
                    <h4>地图选点</h4>
                    <div id="tmap-container" class="tmap-container"></div>
                    <div class="map-actions">
                        <el-button type="primary" @click="getLocationFromMap">初始化地图/重新获取</el-button>
                        <el-button @click="destroyMap">清除地图</el-button>
                    </div>
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelPoint">取消</el-button>
                    <el-button type="primary" @click="savePoint">确定</el-button>
                </span>
            </template>
        </el-dialog>



        <div class="save-button-container">
            <el-button type="primary" @click="saveSecurityData">保存地图标点配置</el-button>
        </div>
    </div>
</template>
<script lang="ts" setup>
    import { ref, reactive } from 'vue'
    import { ElMessage, ElMessageBox } from 'element-plus'
    import { updateDataClassify } from '@/api/port'

    // 定义
    // 模块5: 地图标点配置表单
    const securityForm = reactive({
        mapPoints: [] as Array<{
            name: string
            type: string
            longitude: number
            latitude: number
        }>
    })
    // 规则
    const pointRules = {
        name: [{ required: true, message: '点位名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '点位类型不能为空', trigger: 'change' }],
        longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
        latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }]
    }
    
    // 地图相关状态
    const mapInstance = ref<any>(null)
    const mapLoaded = ref(false)
    // 标点配置弹窗相关
    const pointDialogVisible = ref(false)
    const currentPointIndex = ref(-1)
    const pointForm = reactive({
        name: '',
        type: '',
        longitude: 0,
        latitude: 0
    })

    // 函数交互
    // 地图标点相关函数
    const openAddPointDialog = async () => {
        currentPointIndex.value = -1
        pointForm.name = ''
        pointForm.type = ''
        pointForm.longitude = 0
        pointForm.latitude = 0
        pointDialogVisible.value = true
        let timer = setTimeout(() => {
            getLocationFromMap()
            clearTimeout(timer)
        }, 500)
    }

    // 从地图获取坐标（暂时模拟，等待地图接入）
    const getLocationFromMap = () => {
        // 初始化地图（如果还未初始化）
        if (!mapInstance.value && !mapLoaded.value) {
            initMap()
        } else {
            ElMessage.info('请点击地图获取坐标')
        }
    }

    // 声明腾讯地图全局对象
    declare const TMap: any;

    // 初始化腾讯地图
    const initMap = () => {
        // 检查SDK是否加载
        if (typeof TMap === 'undefined') {
            ElMessage.error('腾讯地图SDK未加载完成，请稍后再试')
            return
        }

        // 创建地图容器
        const mapContainer = document.getElementById('tmap-container')
        if (!mapContainer) {
            ElMessage.error('地图容器未找到')
            return
        }

        try {
            // 初始化地图
            const map = new TMap.Map('tmap-container', {
                center: new TMap.LatLng(39.984104, 116.307503), // 北京坐标
                zoom: 12,
                viewMode: '2D'
            })

            mapInstance.value = map
            mapLoaded.value = true

            // 添加地图点击事件监听
            map.on('click', (evt: any) => {
                const latLng = evt.latLng
                pointForm.longitude = Number(latLng.getLng().toFixed(6))
                pointForm.latitude = Number(latLng.getLat().toFixed(6))
                ElMessage.success(`已获取坐标：${pointForm.longitude}, ${pointForm.latitude}`)
            })

            ElMessage.success('地图初始化成功，请点击地图获取坐标')
        } catch (error) {
            console.error('地图初始化失败:', error)
            ElMessage.error('地图初始化失败，请检查网络连接或API密钥')
        }
    }

    // 销毁地图实例
    const destroyMap = () => {
        if (mapInstance.value) {
            mapInstance.value.destroy()
            mapInstance.value = null
            mapLoaded.value = false
        }
    }
    // 取消按钮
    const cancelPoint = () => {
        pointDialogVisible.value = false
        destroyMap()
    }

    // 获取点位类型标签样式
    const getPointTypeTag = (type: string) => {
        const tagMap: Record<string, string> = {
            solar: 'primary',
            battery: 'warning',
            travel: 'success',
            transport: 'info'
        }
        return tagMap[type] || 'default'
    }

    // 获取点位类型名称
    const getPointTypeName = (type: string) => {
        const nameMap: Record<string, string> = {
            solar: '绿电供应',
            battery: '共享换点',
            travel: '共享出行',
            transport: '共享运力'
        }
        return nameMap[type] || type
    }

    // 编辑点位
    const editPoint = (point: any, index: number) => {
        currentPointIndex.value = index
        pointForm.name = point.name
        pointForm.type = point.type
        pointForm.longitude = point.longitude
        pointForm.latitude = point.latitude
        pointDialogVisible.value = true
        let timer = setTimeout(() => {
            getLocationFromMap()
            clearTimeout(timer)
        }, 500)
    }
    // 删除点位
    const deletePoint = (index: number) => {
        ElMessageBox.confirm('确定要删除这个标点吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            securityForm.mapPoints.splice(index, 1)
            ElMessage.success('删除成功')
        })
    }


    const pointFormRef = ref()
    const savePoint = async () => {
        if (!pointFormRef.value) return
        
        try {
            await pointFormRef.value.validate()
            
            const pointData = {
                name: pointForm.name,
                type: pointForm.type,
                longitude: pointForm.longitude,
                latitude: pointForm.latitude
            }

            if (currentPointIndex.value >= 0) {
                // 编辑模式
                securityForm.mapPoints[currentPointIndex.value] = pointData
                ElMessage.success('标点更新成功')
            } else {
                // 新增模式
                securityForm.mapPoints.push(pointData)
                ElMessage.success('标点添加成功')
            }

            pointDialogVisible.value = false
        } catch (error) {
            ElMessage.warning('请填写完整的标点信息')
        }
    }


    const securityFormRef = ref()
    const saveSecurityData = async () => {
        if (securityForm.mapPoints.length === 0) {
            ElMessage.warning('请至少添加一个地图标点')
            return
        }
        
        await updateDataClassify({
            id: 1,
            key: 'module5',
            value: securityForm
        })
        console.log('保存地图标点配置:', securityForm)
        ElMessage.success('地图标点配置保存成功')
    }

    const init = async (module: any) => {
        if (module) {
            securityForm.mapPoints = module.mapPoints
        }
    }

    defineExpose({
        init
    })
</script>
<style lang="less" scoped>

</style>